﻿using System.Reflection;
using System.Web.Hosting;
using System.Text;
using System.Threading;
using System.Net;
namespace System.Web
{
    public partial class NetHttpRuntime
    {
        public static object InitializationException { get; set; }
        private static bool _firstRequestCompleted;
        //private static int _activeRequestCount;
        //private static bool _beforeFirstRequest;
        //private static RequestTimeoutManager _timeoutManager;

        internal static object CreateNonPublicInstance(Type type, object[] args)
        {
            return Activator.CreateInstance(type, BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, args, null);
        }

        private static void EnsureFirstRequestInit(NetHttpContext context) { }

        private void Init()
        {
            try
            {
                if (Environment.OSVersion.Platform != PlatformID.Win32NT)
                    throw new PlatformNotSupportedException("RequiresNT");
                _handlerCompletionCallback = new AsyncCallback(OnHandlerCompletion);
                _asyncEndOfSendCallback = new NetHttpWorkerRequest.EndOfSendNotification(EndOfSendCallback);
            }
            catch (Exception e) { InitializationException = e; }
        }

        private void OnHandlerCompletion(IAsyncResult ar)
        {
            var asyncState = (NetHttpContext)ar.AsyncState;
            try { asyncState.AsyncAppHandler.EndProcessRequest(ar); }
            catch (Exception exception) { asyncState.AddError(exception); }
            finally { asyncState.AsyncAppHandler = null; }
            //FinishRequest(null, asyncState.WorkerRequest, asyncState, asyncState.Error);
        }

        private void EndOfSendCallback(NetHttpWorkerRequest wr, object arg)
        {
            var context = (NetHttpContext)arg;
            ((NetHttpRequest)context.Request).Dispose();
            ((NetHttpResponse)context.Response).Dispose();
        }


        internal static void RaiseRuntimeError(Exception e, object source)
        {
            Console.WriteLine(e.Message);
        }
    }
}
